package com.jiang.service;

import com.jiang.Domain.Message;
import com.jiang.Domain.MessageType;

import java.io.*;

/**
 * @author Jiang
 * @version 1.0
 * @date 2023/12/1 15:36
 * 完成文件的传输
 */
public class FileClientService {
    public void sendFileToOne(String src, String dest, String senderId, String getterId) {
        // 读取src文件 ==> message
        Message message = new Message();
        message.setMesType(MessageType.MESSAGE_FILE_MES);
        message.setSender(senderId);
        message.setGetter(getterId);
        message.setSrc(src);
        message.setDest(dest);

        FileInputStream fileInputStream = null;
        byte[] bytes = new byte[(int) new File(src).length()];

        try {
            fileInputStream = new FileInputStream(src);
            fileInputStream.read(bytes); // 将src的文件读入到字节数组中
            // 将文件对应的字节数组设置message
            message.setFileBytes(bytes);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        System.out.println("\n" + message.getSender() + "给" + getterId + "发送文件：" + src + " 到对方电脑目录" + dest);

        // 发送
        try {
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(ManageClientConnectServerThread.getClientConnectServerThread(message.getSender()).getSocket().getOutputStream());
            objectOutputStream.writeObject(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
